import React, { useState, useEffect } from 'react';
import {
    Container,
    Box,
    Typography,
    Button,
    Paper,
    Breadcrumbs,
    Link as MuiLink,
    CircularProgress,
    Alert,
    Tabs,
    Tab,
    TextField
} from '@mui/material';
import {
    ArrowBack as ArrowBackIcon,
    Home as HomeIcon,
    ViewInAr as ModelIcon,
    Edit as EditIcon,
    Tune as TuneIcon,
    Upload as UploadIcon
} from '@mui/icons-material';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { motion } from 'framer-motion';
import { styled } from '@mui/material/styles';

import { useModelContext } from '../contexts/ModelContext';
import ThreeModelEditor from '../components/ThreeModelEditor';
import modelService from '../services/modelService';

const StyledTab = styled(Tab)(({ theme }) => ({
    textTransform: 'none',
    fontSize: '1rem',
    fontWeight: 500,
    minHeight: 48,
    padding: '0 16px',
    '&.Mui-selected': {
        color: theme.palette.primary.main,
        fontWeight: 600
    }
}));

const GeometryModelEdit = () => {
    const { id } = useParams();
    const navigate = useNavigate();
    const {
        loading: contextLoading,
        updateModel,
        updateModelGeometry,
    } = useModelContext();

    const [model, setModel] = useState(null);
    const [loadingModel, setLoadingModel] = useState(true);
    const [notFound, setNotFound] = useState(false);
    const [tabValue, setTabValue] = useState(0);
    const [modelName, setModelName] = useState('');
    const [modelDescription, setModelDescription] = useState('');
    const [error, setError] = useState(null);

    // 加载模型数据
    useEffect(() => {
        const loadModel = async () => {
            if (!id) {
                setNotFound(true);
                setLoadingModel(false);
                return;
            }
            setLoadingModel(true);
            setError(null);
            try {
                const response = await modelService.getModel(id);
                const fetchedModel = response.data || response;

                if (fetchedModel) {
                    console.log("[GeometryModelEdit] 成功获取单个模型数据:", fetchedModel);
                    setModel(fetchedModel);
                    setModelName(fetchedModel.name || '');
                    setModelDescription(fetchedModel.description || '');
                    setNotFound(false);
                } else {
                    console.warn(`[GeometryModelEdit] modelService.getModel(${id}) 未找到模型`);
                    setNotFound(true);
                }
            } catch (err) {
                console.error(`[GeometryModelEdit] modelService.getModel(${id}) 失败:`, err);
                setError(err.message || '加载模型数据失败');
                setNotFound(true);
            } finally {
                setLoadingModel(false);
            }
        };

        loadModel();
    }, [id]);

    // 处理几何体更新
    const handleGeometryUpdate = async (geometryData) => {
        try {
            setError(null);
            // 获取最新的模型数据，确保包含additionalObjects
            const updatedGeometry = {
                geometry: geometryData.geometry || geometryData,
                additionalObjects: geometryData.additionalObjects || []
            };
            await updateModelGeometry(id, updatedGeometry);
            // 强制刷新模型列表
            await fetchModels();
            // 成功提示
            alert('模型几何体已成功更新！');
            navigate('/models');
        } catch (err) {
            console.error('更新几何体失败:', err);
            setError(err.message || '更新几何体失败，请稍后再试');
        }
    };

    // 处理模型信息更新（不含几何体）
    const handleInfoUpdate = async (basicInfo) => {
        try {
            setError(null);
            await updateModel(id, basicInfo);
            // 强制刷新模型列表
            await fetchModels();
            // 成功提示
            alert('模型基本信息已成功更新！');
            navigate('/models');
        } catch (err) {
            console.error('更新模型信息失败:', err);
            setError(err.message || '更新模型信息失败，请稍后再试');
        }
    };

    // 处理返回
    const handleGoBack = () => {
        navigate('/models');
    };

    // 从THREE模型编辑器保存
    const handleSaveFromEditor = (modelData) => {
        const saveData = {
            ...modelData,
            name: modelName,
            description: modelDescription
        };

        if (tabValue === 0) {
            console.log("[GeometryModelEdit] 保存几何体，包含信息:", saveData);
            handleFullUpdate(saveData);
        } else {
            console.log("[GeometryModelEdit] 保存基本信息:", { name: modelName, description: modelDescription });
            handleInfoUpdate({ name: modelName, description: modelDescription });
        }
    };

    // 处理完整模型更新
    const handleFullUpdate = async (fullModelData) => {
        try {
            setError(null);
            console.log("[GeometryModelEdit] 尝试完整更新模型:", id, fullModelData);
            await updateModel(id, fullModelData);
            alert('模型已成功更新！');
            navigate('/models');
        } catch (err) {
            console.error('完整更新模型失败:', err);
            setError(err.message || '更新模型失败，请稍后再试');
        }
    };

    // 处理模型名称变更
    const handleNameChange = (event) => {
        setModelName(event.target.value);
    };

    // 处理模型描述变更
    const handleDescriptionChange = (event) => {
        setModelDescription(event.target.value);
    };

    // 显示"未找到"错误
    if (notFound && !loadingModel) {
        return (
            <Container maxWidth="md" sx={{ py: 8, textAlign: 'center' }}>
                <Alert severity="error" sx={{ mb: 4 }}>
                    找不到ID为 {id} 的模型
                </Alert>
                <Button
                    variant="contained"
                    startIcon={<ArrowBackIcon />}
                    onClick={handleGoBack}
                >
                    返回模型列表
                </Button>
            </Container>
        );
    }

    // 处理加载状态
    if (loadingModel) {
        return (
            <Container maxWidth="md" sx={{ py: 8, textAlign: 'center' }}>
                <CircularProgress sx={{ mb: 2 }} />
                <Typography>正在加载模型数据...</Typography>
            </Container>
        );
    }

    return (
        <Container maxWidth="xl" sx={{ py: 4 }}>
            <Box sx={{ mb: 4 }}>
                <Breadcrumbs aria-label="breadcrumb" sx={{ mb: 2 }}>
                    <MuiLink
                        component={Link}
                        to="/"
                        underline="hover"
                        sx={{ display: 'flex', alignItems: 'center' }}
                    >
                        <HomeIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        首页
                    </MuiLink>
                    <MuiLink
                        component={Link}
                        to="/models"
                        underline="hover"
                        sx={{ display: 'flex', alignItems: 'center' }}
                    >
                        <ModelIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        模型列表
                    </MuiLink>
                    <Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
                        <TuneIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        编辑几何体模型
                    </Typography>
                </Breadcrumbs>

                <Paper
                    component={motion.div}
                    initial={{ opacity: 0, y: -20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5 }}
                    elevation={0}
                    sx={{
                        p: 3,
                        backgroundImage: 'linear-gradient(120deg, #e0f7fa 0%, #bbdefb 100%)',
                        borderRadius: 4,
                        mb: 4,
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center'
                    }}
                >
                    <Box>
                        <Typography variant="h4" component="h1" sx={{ fontWeight: 700 }}>
                            编辑几何体模型
                        </Typography>
                        <Typography variant="body1" color="text.secondary">
                            {model ? `编辑 "${model.name}"` : '加载模型信息...'}
                        </Typography>
                    </Box>
                    <Box sx={{ display: 'flex', gap: 2 }}>
                        <Button
                            variant="contained"
                            color="primary"
                            startIcon={<UploadIcon />}
                            component={Link}
                            to={`/models/${id}/files`}
                            sx={{ display: model ? 'flex' : 'none' }}
                        >
                            文件管理
                        </Button>
                        <Button
                            variant="contained"
                            startIcon={<ArrowBackIcon />}
                            onClick={handleGoBack}
                            component={motion.button}
                            whileHover={{ scale: 1.05 }}
                            whileTap={{ scale: 0.95 }}
                        >
                            返回列表
                        </Button>
                    </Box>
                </Paper>
            </Box>

            {error && (
                <Alert severity="error" sx={{ mb: 3 }}>
                    {error}
                </Alert>
            )}

            <Paper sx={{ mb: 4 }}>
                <Tabs
                    value={tabValue}
                    onChange={(e, newValue) => setTabValue(newValue)}
                    variant="fullWidth"
                    indicatorColor="primary"
                    textColor="primary"
                    sx={{ borderBottom: 1, borderColor: 'divider' }}
                >
                    <StyledTab label="几何体编辑" icon={<EditIcon />} iconPosition="start" />
                    <StyledTab label="基本信息" icon={<TuneIcon />} iconPosition="start" />
                </Tabs>
            </Paper>

            {tabValue === 0 && model && (
                <ThreeModelEditor
                    key={model.id}
                    initialModel={model}
                    onSave={handleSaveFromEditor}
                    modelName={modelName}
                    modelDescription={modelDescription}
                />
            )}

            {tabValue === 1 && model && (
                <Paper sx={{ p: 3 }}>
                    <Typography variant="h6" gutterBottom>编辑基本信息</Typography>
                    <TextField
                        label="模型名称"
                        value={modelName}
                        onChange={handleNameChange}
                        fullWidth
                        margin="normal"
                    />
                    <TextField
                        label="模型描述"
                        value={modelDescription}
                        onChange={handleDescriptionChange}
                        fullWidth
                        margin="normal"
                        multiline
                        rows={4}
                    />
                    <Button
                        variant="contained"
                        color="primary"
                        onClick={() => handleInfoUpdate({ name: modelName, description: modelDescription })}
                        sx={{ mt: 2 }}
                    >
                        保存基本信息
                    </Button>
                </Paper>
            )}
        </Container>
    );
};

export default GeometryModelEdit; 